/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.utl.ist.isr.livetrack.server.impl;

import pt.utl.ist.isr.livetrack.server.interfaces.AxisCamera;
import pt.utl.ist.isr.livetrack.analysis.ImageUtils;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.IOException;
import java.net.URL;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

/**
 *
 * @author David Miguel Antunes <davidmiguel [ at ] antunes.net>
 */
public class AxisCameraImpl extends DefaultCamera implements AxisCamera {

    private String hostname;
    private BufferedImage bi;

    public AxisCameraImpl() {
        super();
    }

    public AxisCameraImpl(String hostname, String id) {
        super(id);
        this.hostname = hostname;
    }

    @Override
    public String getHostname() {
        return hostname;
    }

    @Override
    public void setHostname(String hostname) {
        this.hostname = hostname;
    }

    @Override
    public String getType() {
        return getClass().getSimpleName().replace("Impl", "");
    }

    @Override
    public synchronized void acquireImage() {
        try {
            String url = "http://" + hostname + "/axis-cgi/jpg/image.cgi?compression=0";

            ImageInputStream iis = ImageIO.createImageInputStream(new URL(url).openConnection().getInputStream());

            String extension = "jpg";

            Iterator readers = ImageIO.getImageReadersByFormatName(extension);
            ImageReader reader = (ImageReader) readers.next();

            reader.setInput(iis, true);

            ImageReadParam param = reader.getDefaultReadParam();

            WIDTH = reader.getWidth(0);
            HEIGHT = reader.getHeight(0);

            if (bi == null || bi.getWidth() != WIDTH || bi.getHeight() != HEIGHT) {
                WritableRaster wr = Raster.createInterleavedRaster(DataBuffer.TYPE_USHORT, WIDTH, HEIGHT, 3, null);
                bi = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
                bi.setData(wr);
            }

            param.setDestination(bi);

            bi = reader.read(0, param);

            NCOMP = bi.getColorModel().getNumComponents();

            if (iu == null || !iu.valid(WIDTH, HEIGHT, NCOMP)) {
                iu = new ImageUtils(WIDTH, HEIGHT, NCOMP);
            }
            if (img == null || img.length != WIDTH * HEIGHT * NCOMP) {
                img = iu.newImage();
            }

            iu.bufferedImageToArray(bi, img);

        } catch (IOException ex) {
            logger.error(ex);
        }
        processNewImage();
    }

    @Override
    protected void postprocessImage(BufferedImage bi) {
    }
}
